#!/usr/bin/awk -f
# Nginx日志分析脚本
# 分析访问日志，统计状态码、IP访问量、请求路径等

BEGIN {
    print "=== Nginx 日志分析报告 ==="
    print "分析时间:", strftime("%Y-%m-%d %H:%M:%S")
    print "================================"
    total = 0
    status_2xx = 0
    status_3xx = 0
    status_4xx = 0
    status_5xx = 0
}

# 主处理逻辑
{
    total++
    ip = $1
    timestamp = $4
    method = $6
    url = $7
    status = $9
    size = $10
    
    # 统计IP访问次数
    ip_count[ip]++
    
    # 统计状态码分布
    if (status ~ /^2/) status_2xx++
    else if (status ~ /^3/) status_3xx++
    else if (status ~ /^4/) status_4xx++
    else if (status ~ /^5/) status_5xx++
    
    # 统计请求方法
    gsub(/["]/, "", method)
    method_count[method]++
    
    # 统计URL访问量
    url_count[url]++
    
    # 统计流量
    if (size ~ /^[0-9]+$/) {
        total_bytes += size
    }
    
    # 记录错误请求
    if (status ~ /^[45]/) {
        error_log[total] = sprintf("%s %s %s %s", ip, status, method, url)
    }
}

END {
    print "\n📊 总体统计"
    print "总请求数:", total
    printf "总流量: %.2f MB\n", total_bytes/1024/1024
    printf "平均请求大小: %.2f KB\n", total_bytes/total/1024
    
    print "\n📈 状态码分布"
    printf "2xx (成功): %d (%.1f%%)\n", status_2xx, status_2xx*100/total
    printf "3xx (重定向): %d (%.1f%%)\n", status_3xx, status_3xx*100/total
    printf "4xx (客户端错误): %d (%.1f%%)\n", status_4xx, status_4xx*100/total
    printf "5xx (服务器错误): %d (%.1f%%)\n", status_5xx, status_5xx*100/total
    
    print "\n🌐 Top 10 访问IP"
    # 对IP按访问次数排序
    n = asorti(ip_count, sorted_ips, "@val_num_desc")
    for (i = 1; i <= (n > 10 ? 10 : n); i++) {
        printf "%-15s: %d 次\n", sorted_ips[i], ip_count[sorted_ips[i]]
    }
    
    print "\n📋 请求方法统计"
    for (method in method_count) {
        printf "%-8s: %d 次\n", method, method_count[method]
    }
    
    print "\n🔥 Top 10 热门URL"
    n = asorti(url_count, sorted_urls, "@val_num_desc")
    for (i = 1; i <= (n > 10 ? 10 : n); i++) {
        printf "%-30s: %d 次\n", sorted_urls[i], url_count[sorted_urls[i]]
    }
    
    if (status_4xx + status_5xx > 0) {
        print "\n❌ 错误请求详情"
        for (line_num in error_log) {
            print error_log[line_num]
        }
    }
    
    print "\n================================"
    print "分析完成 ✅"
}